<!--
 * @Description:水平滚动条
 * @Author: Sun
 * @Date: 2019-07-01 20:05:50
 * @LastEditors: Sun
 * @LastEditTime: 2019-07-20 08:46:46
 -->
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>水平滚动条</title>
	<style>
	*{
		margin: 0; padding: 0;
	}
	.scroll{
		width: 400px;
		height: 8px;
		background-color: #cccc;
		margin: 100px;
		position: relative;
	}
	.bar{
		width: 15px;
		height: 20px;
		margin-top: -7px;
		background-color: #369;
		position: absolute;
		top: 2px;
		left: 0;
		cursor: pointer;
	}
	.mask{
		width: 0;
		height: 100%;
		background: #369;
		position: absolute;
		left: 0;
		top: 0;
	}
	
	</style>
	<script>
		window.onload = function () {
		  let scrollBar=document.getElementById("scrollBar")
			let demo=document.getElementById("deom")
			var bar=scrollBar.children[0]
			var mask=scrollBar.children[1]

			
			bar.onmousedown=function(event){ //按下事件
			
			var event=event||window.event
			// var leftval=event.clientX-scrollBar.offsetLeft; //拖动块在横线的距离
				var leftval=event.clientX-this.offsetLeft; //拖动块固定到左边的距离
       //拖动一定要写在 down里面
			 var that=this
				document.onmousemove=function(event){//拖动
						var event=event||window.event
						// bar.style.left=event.clientX-leftval-scrollBar.offsetLeft+"px";
						that.style.left=event.clientX-leftval+"px";//拖动块在父级游走的距离
						var val=parseInt(that.style.left)
						if(val<0){
               that.style.left=0;
						}else if(val>scrollBar.offsetWidth-bar.offsetWidth){
							that.style.left=scrollBar.offsetWidth-bar.offsetWidth+"px";
						}
						mask.style.width=that.style.left //滚动条位置
						demo.innerHTML=//计算百分比 
						"已经走了:"+ parseInt(
							parseInt(that.style.left)/(scrollBar.offsetWidth-bar.offsetWidth)
						*100)+"%"
						window.getSelection?window.getSelection().removeAllRanges():document.selection.empty
				}
				document.onmouseup=function(event){//弹起
					document.onmousemove=null
					
				
				}

			}
		}
	</script>
</head>

<body>
  <div class="scroll" id="scrollBar">
		<div class="bar" id="bar"></div>
		<div class="mask"></div>
	</div>
	<div id="deom"></div>	
</body>

</html>